package com.qf.Interceptor;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import sun.security.util.Resources;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 25/11/2019
 * Echo
 * qmxc
 * Alibaba
 */
public class PoweInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.先判断是否为匿名地址
        String uri = request.getRequestURI();
        ResourceBundle anno = Resources.getBundle("anno");
        if (anno.containsKey(uri)) {
            return true;
        }
        //2.判断是否为公共地址
        ResourceBundle aPublic = Resources.getBundle("public");
        if (aPublic.containsKey(uri)) {
            return true;
        }

        //3.判断是否为符合用户权限的地址
        HttpSession session = request.getSession();
        Employee user = (Employee) session.getAttribute("user");
        List<Menu> menuList = user.getRole().getMenuList();
        for (Menu menu : menuList) {
            String url = menu.getUrl();
            if (uri.equals(menu.getUrl())) {
                return true;
            } else {
                List<Menu> secondList = menu.getSecondList();
                for (Menu menu1 : secondList) {
                    if (uri.equals(menu1.getUrl())){
                        return true;
                    }
                }
            }
        }
        List<Menu> permissions = user.getRole().getPermission();
        for (Menu permission : permissions) {
            if (uri.equals(permission.getUrl())){
                return true;
            }
        }
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("<script>alert('请登录权限更高的账号');location.href='/exit';</script>");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
